package org.grottarossa.data;


import java.util.ArrayList;
import java.util.List;

import org.grottarossa.data.exception.DataSourceException;
import org.grottarossa.data.exception.DataSourceException.DataSourceErrorCode;
import org.grottarossa.data.exception.QueryException;
import org.grottarossa.driver.ECMBuilderTemplate;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
*
* La classe rappresenta il provider dei dati provenienti dai sistemi di back end.
* Il provider viene utilizzato dai componenti della GUI predisposti alla visualizzazione
* di tali dati (tabelle o combo box).
*
* @author Marco Sabatini (sabatini.m@gmail.com)
* @author Maurizio Farina (maurizio.farina@gmail.com)
* @author Marco Trischitta ()
* 
* @version %I%, %G%
* @since 1.0
*
* */
public class DataProvider
{
	/**Il campo rappresenta la lista di datasource registrati e dai quali vengono recuperati i dati assegnati a
	 * determinati fields
	 * */
	private List<DataSource> m_sources;
	private final ECMBuilderTemplate m_builder;

	/**Il costruttore alloca la lista contenente i data sources
	 * @param builder */
	public DataProvider(ECMBuilderTemplate builder)
	{
		this.m_builder = builder;
		this.m_sources = new ArrayList<DataSource>();

		ApplicationContext context = new ClassPathXmlApplicationContext("aeroflow-provider.xml");
		DataProviderService service = (DataProviderService)context.getBean("providerService");

		this.m_sources = service.getSources();

		for(DataSource ds : m_sources)
		{
			try
			{
				ds.initialize(builder);
			}
			catch(Exception ex)
			{
				ex.printStackTrace();
			}
		}
	}

	public void addDataSource(DataSource source)
	{
		m_sources.add(source);
	}

	public Query getSource(String field, QueryFilter filter) throws DataSourceException, QueryException
	{
		for (DataSource entry : m_sources) {

			if ( entry.manageField(field) )
			{
				return entry.getQuery(field, filter);
			}
		}

		throw new DataSourceException("Field: " + field+" not found", DataSourceErrorCode.DATASOURCE_NOT_FOUND);
	}
}
